<template>
  <el-dialog
    append-to-body
    title="密码修改"
    :visible.sync="dialogShow"
    width="60%"
    :before-close="beforeClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    custom-class="my-dialog form-top"
    center>
    <el-form :rules="rules" ref="form" :model="form">
      <el-form-item label="旧密码：" prop="oldPwd" label-width="120px">
        <el-input placeholder="请输入旧密码" v-model.trim="form.oldPwd" @input="removeKong(1)" show-password clearable></el-input>
      </el-form-item>
      <el-form-item label="新密码：" prop="newPwd" label-width="120px">
        <el-input placeholder="请设置新密码" v-model.trim="form.newPwd" @input="removeKong(2)" show-password clearable></el-input>
        <div class="intensity">
          <span class="psdText">密码强度</span>
          <span
            class="line"
            :class="[level.includes('low') ? 'low' : '']"
          ></span>
          <span
            class="line"
            :class="[level.includes('middle') ? 'middle' : '']"
          ></span>
          <span
            class="line"
            :class="[level.includes('high') ? 'high' : '']"
          ></span>
        </div>
      </el-form-item>
      <el-form-item label="确认密码：" prop="confirmPwd" label-width="120px">
        <el-input placeholder="请再次输入密码" v-model.trim="form.confirmPwd" @input="removeKong(3)" show-password clearable></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button type="primary" class="dialog-btn" :loading="loading" @click="submitBtn('form')">确 定</el-button>
      </span>
  </el-dialog>
</template>

<script>
import md5 from "js-md5";
import { updatePassword } from "@/api/user.js";
export default {
  props: {
    dialogShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    var validateNewPwd = (rule, value, callback) => {
      if (value === '') {
        this.level = []
        callback(new Error('请输入新密码'));
      } else if (value.length < 6) {
        callback(new Error('密码应多于6位'));
      } else if (value.length > 16) {
        callback(new Error('密码应少于16位'));
      } else {
        callback();
      }
    };
    var validateIntensityPwd = (rule, value, callback) => {
      // 校验是数字
      const regex1 = /^\d+$/
      // 校验字母
      const regex2 = /^[A-Za-z]+$/
      // 校验符号
      const regex3 = /^[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、]+$/
      if (regex1.test(value)) {
        this.level = ['low'];
        callback(new Error('密码强度不足，必须包含字母、数字、特殊符号'));
      } else if (regex2.test(value)) {
        this.level = ['low'];
        callback(new Error('密码强度不足，必须包含字母、数字、特殊符号'));
      } else if (regex3.test(value)) {
        this.level = ['low'];
        callback(new Error('密码强度不足，必须包含字母、数字、特殊符号'));
      } else if (/^[A-Za-z\d]+$/.test(value)) {
        this.level = ['low', 'middle'];
        callback(new Error('密码强度不足，必须包含字母、数字、特殊符号'));
      } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、\d]+$/.test(value)) {
        this.level = ['low', 'middle'];
        callback(new Error('密码强度不足，必须包含字母、数字、特殊符号'));
      } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z]+$/.test(value)) {
        this.level = ['low', 'middle'];
        callback(new Error('密码强度不足，必须包含字母、数字、特殊符号'));
      } else if (/^[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、A-Za-z\d]+$/.test(value)) {
        this.level = ['low', 'middle', 'high'];
        callback();
      } else {
        callback();
      }
    };
    var validateConfirmPwd = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'));
      } else if (value !== this.form.newPwd) {
        callback(new Error('两次输入密码不一致'));
      } else {
        callback();
      }
    };
    return {
      form: {
        oldPwd: '',// 旧密码
        newPwd: '',// 新密码
        confirmPwd: '',// 确认新密码
      },
      rules: {
        oldPwd: [
          {required: true, message: "请输入旧密码", trigger: ['blur', 'change']}
        ],
        newPwd: [
          {required: true, validator: validateNewPwd, trigger: ['blur', 'change']},
          {required: true, validator: validateIntensityPwd, trigger: "change"},
          {
            pattern: /^[^\u4e00-\u9fa5 ]{6,16}$/,
            message: '密码不能包含中文或者空格',
            trigger: 'blur'
          }
        ],
        confirmPwd: [
          {required: true, validator: validateConfirmPwd, trigger: ['blur', 'change']}
        ]
      },
      level: [],
      loading: false
    }
  },
  methods: {
    beforeClose() {
      this.level= [];
      this.$refs.form.resetFields();
      this.$emit('dialogClose', false)
    },
    removeKong(type) {
      if (type === 1) {
        this.form.oldPwd = this.form.oldPwd.replace(/\s/g, '');
      }
      if (type === 2) {
        this.form.newPwd = this.form.newPwd.replace(/\s/g, '');
      }
      if (type === 3) {
        this.form.confirmPwd = this.form.confirmPwd.replace(/\s/g, '');
      }
    },
    async submitBtn(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let params = {
            oldPassword: md5(this.form.oldPwd),
            newPassword: md5(this.form.newPwd)
          };
          await updatePassword(params).then(res => {
            if (res) {
              this.$message.success("修改成功");
              this.$refs.form.resetFields()
              this.$emit("dialogClose");
            } else {
              this.$message({
                showClose: true,
                message: '修改失败',
                type: "error"
              });
            }
          });
        }
      })
    }
  },
  watch: {},
  mounted() {}

}
</script>

<style scoped lang="scss">

.intensity {
  .psdText {
    color: #FFFFFF;
    font-size: 14px;
    margin-right: 10px;
  }

  .line {
    display: inline-block;
    width: 30px;
    height: 4px;
    background: #d8d8d8;
    border-radius: 3px;
    margin-right: 8px;

    &.low {
      background: #f4664a;
    }

    &.middle {
      background: #ffb700;
    }

    &.high {
      background: #2cbb79;
    }
  }

  .level {
    margin: 0 16px 0 8px;
  }

  .warningtext {
    color: #5a5a5a;
    font-size: 12px;
    margin-top: 5px;
  }
}
</style>
